package com.lou.springboot.controller.blog;

import com.lou.springboot.common.PageResult;
import com.lou.springboot.common.ResultVO;
import com.lou.springboot.common.ResultVOUtil;
import com.lou.springboot.controller.admin.BaseController;
import com.lou.springboot.dao.BlogCommentDao;
import com.lou.springboot.entity.BlogComment;
import com.lou.springboot.entity.BlogDetailVO;
import com.lou.springboot.entity.BlogListVO;
import com.lou.springboot.enums.ArticleTypeEnum;
import com.lou.springboot.enums.ResultEnum;
import com.lou.springboot.service.BlogService;
import com.lou.springboot.service.BlogTagService;
import com.lou.springboot.service.CommentService;
import com.lou.springboot.utils.JsonUtils;
import com.lou.springboot.utils.MyBlogUtils;
import com.lou.springboot.utils.PatternUtil;
import com.lou.springboot.utils.RedisOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


@Controller
public class MyBlogController extends BaseController {

    @Autowired
    private BlogService blogService;
    @Autowired
    private BlogTagService tagService;
    @Autowired
    private CommentService commentService;

    @Autowired
    private RedisOperator redisOperator;

    @GetMapping({"/", "/index", "index.html"})
    public String index(HttpServletRequest request) {
        return this.page(request, 1);
    }

    @GetMapping({"/page/{pageNum}"})
    public String page(HttpServletRequest request,
                       @PathVariable Integer pageNum) {
        PageResult pageResult = blogService.getBlogsForIndexPage(pageNum);

        if (blogService == null) {
            return "error/error_404";
        }
        request.setAttribute("blogPageResult", pageResult);
        request.setAttribute("newBlogs", blogService.getBlogListForIndexPage(ArticleTypeEnum.LATEST_ARTICLE.getCode()));
        request.setAttribute("hotBlogs", blogService.getBlogListForIndexPage(ArticleTypeEnum.HOT_ARTICLE.getCode()));
        request.setAttribute("hotTags", tagService.getBlogTagCountForIndex());
        request.setAttribute("pageName", "首页");
        return "blog/index";
    }

    @GetMapping("/search/{keyword}")
    public String search(HttpServletRequest request,
                         @PathVariable("keyword") String keyword) {
        return search(request, keyword, 1);
    }

    @GetMapping("/search/{keyword}/{page}")
    public String search(HttpServletRequest request,
                         @PathVariable("keyword") String keyword,
                         @PathVariable("page") Integer page) {
        PageResult pageResult = blogService.getBlogsPageBySearch(keyword, page);
        request.setAttribute("blogPageResult", pageResult);
        request.setAttribute("pageName", "搜索");
        request.setAttribute("pageUrl", "search");
        request.setAttribute("keyword", keyword);
        return "blog/list";
    }

    @GetMapping("/tag/{tagName}")
    public String searchByTagName(HttpServletRequest request,
                                  @PathVariable("tagName") String tagName) {
        return searchByTagName(request, tagName, 1);
    }

    @GetMapping("/tag/{tagName}/{page}")
    public String searchByTagName(HttpServletRequest request,
                                  @PathVariable("tagName") String tagName,
                                  @PathVariable("page") Integer page) {
        PageResult pageResult = blogService.getBlogsPageByTagName(tagName, page);
        request.setAttribute("blogPageResult", pageResult);
        request.setAttribute("pageName", "标签");
        request.setAttribute("pageUrl","tag");
        request.setAttribute("keyword",tagName);
        return "blog/list";
    }

    @GetMapping("/category/{categoryName}")
    public String category(HttpServletRequest request,
                           @PathVariable("categoryName") String categoryName) {
        return category(request,categoryName,1);
    }

    @GetMapping("/category/{categoryName}/{page}")
    public String category(HttpServletRequest request,
                           @PathVariable("categoryName") String categoryName,
                           @PathVariable("page") Integer page){
        PageResult pageResult = blogService.getBlogsPageByCategoryName(categoryName,page);
        request.setAttribute("blogPageResult", pageResult);
        request.setAttribute("pageName", "分类");
        request.setAttribute("pageUrl","category");
        request.setAttribute("keyword",categoryName);
        return "blog/list";
    }

    @GetMapping("/blog/{blogId}")
    public String detail(HttpServletRequest request,
                         @PathVariable("blogId") Long blogId,
                         @RequestParam(value = "commentPage", required = false, defaultValue = "1") Integer commentPage) {
//        String blogDetailRedisKey = FRONT_BLOG_DETAIL_REDIS_PREFIX + blogId;
//        String blogDetailString = redisOperator.get(blogDetailRedisKey);
        BlogDetailVO blogDetailVO;
//        if (blogDetailString != null) {
//            blogDetailVO = JsonUtils.jsonToPojo(blogDetailString, BlogDetailVO.class);
//            blogDetailVO.setBlogViews(blogDetailVO.getBlogViews() + 1);
//            blogService.increaseBlogViews(blogId);
//            redisOperator.set(blogDetailRedisKey, JsonUtils.objectToJson(blogDetailVO));
//        } else {
//            blogDetailVO = blogService.getBlogDetail(blogId);
//            redisOperator.set(blogDetailRedisKey, JsonUtils.objectToJson(blogDetailVO));
//        }
        blogDetailVO = blogService.getBlogDetail(blogId);

        if (blogDetailVO != null) {
            request.setAttribute("blogDetailVO", blogDetailVO);
            request.setAttribute("commentPageResult", commentService.getCommentPageByBlogIdAndPageNum(blogId, commentPage));
        }

        request.setAttribute("pageName", "详情");
        return "blog/detail";
    }

    /**
     * 评论操作
     */
    @PostMapping(value = "/blog/comment")
    @ResponseBody
    public ResultVO comment(HttpServletRequest request,
                            HttpSession session,
                            @RequestParam Long blogId,
                            @RequestParam String verifyCode,
                            @RequestParam String commentator,
                            @RequestParam String email,
                            @RequestParam String websiteUrl,
                            @RequestParam String commentBody) {
        if (StringUtils.isEmpty(verifyCode)) {
            return ResultVOUtil.error("验证码不能为空");
        }
        String kaptchaCode = session.getAttribute("verifyCode") + "";
        if (StringUtils.isEmpty(kaptchaCode)) {
            return ResultVOUtil.error("非法请求");
        }
        if (!verifyCode.equals(kaptchaCode)) {
            return ResultVOUtil.error("验证码错误");
        }
        String ref = request.getHeader("Referer");
        if (StringUtils.isEmpty(ref)) {
            return ResultVOUtil.error("非法请求");
        }
        if (null == blogId || blogId < 0) {
            return ResultVOUtil.error("非法请求");
        }
        if (StringUtils.isEmpty(commentator)) {
            return ResultVOUtil.error("请输入称呼");
        }
        if (StringUtils.isEmpty(email)) {
            return ResultVOUtil.error("请输入邮箱地址");
        }
        if (!PatternUtil.isEmail(email)) {
            return ResultVOUtil.error("请输入正确的邮箱地址");
        }
        if (StringUtils.isEmpty(commentBody)) {
            return ResultVOUtil.error("请输入评论内容");
        }
        if (commentBody.trim().length() > 200) {
            return ResultVOUtil.error("评论内容过长");
        }
        BlogComment blogComment = new BlogComment();
        blogComment.setBlogId(blogId);
        blogComment.setCommentator(MyBlogUtils.cleanString(commentator));
        blogComment.setEmail(email);
        if (PatternUtil.isURL(websiteUrl)) {
            blogComment.setWebsiteUrl(websiteUrl);
        }
        blogComment.setCommentBody(MyBlogUtils.cleanString(commentBody));
        if (!commentService.addComment(blogComment)) {
            return ResultVOUtil.error("发送评论失败");
        } else {
            return ResultVOUtil.success();
        }
    }

}
